# -*- coding:utf-8 -*-

"""
    设置zip包的使用域，包含测试和正式域 test online
"""

import tornado.web
from service import base
from utils.routes import route
from utils import log as logger
from utils import mongo
from configure import config


@route('/manage/scope/?', 'manage.scope')
class ScopeHandler(base.BaseWebHandler):
    """ 设置zip使用域
    """
    db_name = config.DB_NAME
    collection_name = config.COLLECTION_DATAS

    @tornado.web.asynchronous
    @tornado.gen.engine
    def get(self, *argl, **argd):
        scope = self.get_argument('scope', None)
        _id = self.get_argument('_id', None)

        results = {
                   'code':          0,
                   'info':          'set scope success!',
                   'scope':         scope,
                   '_id':           _id,
                   }
        
        if scope not in ['test', 'online'] or not _id:
            results['code'] = 1
            results['info'] = 'params error!'
            self.finish(results)
            return

        spec = {'_id': _id}
        r = yield tornado.gen.Task(mongo.find_one, self.db_name, self.collection_name, spec)
        if not r:
            logger.debug('could not find datas, results =', results, caller=self)
            results['code'] = 1
            results['info'] = 'could not find!'
            self.finish(results)
            return

        fields = {'scope': scope}
        if scope == 'online':
            fields['status'] = '0'          # 如果由测试域转为正式域，设置状态为未激活
            fields['device_scope'] = '1'    # 仅白名单可更新
        r = yield tornado.gen.Task(mongo.update, self.db_name, self.collection_name, spec, fields)
        if not r:
            logger.error('update scope error! results =', results, caller=self)
            results['code'] = 2
            results['info'] = 'update failed!'
            self.finish(results)
            return

        self.finish(results)
        logger.info('update success! results =', results, caller=self)

    @tornado.web.asynchronous
    @tornado.gen.engine
    def post(self, *argl, **argd):
        self.get(*argl, **argd)

